<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { login, register } from '@/api/user'
import { useStore } from '@/store'

const router = useRouter()
const userStore = useStore()

// 当前激活的面板
const activeTab = ref('login')

// 登录表单
const loginForm = reactive({
  username: '',
  password: ''
})

// 注册表单
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  email: '',
  phone: ''
})

// 表单验证规则
const loginRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应为3-20个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度最少为6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// 表单引用
const loginFormRef = ref(null)
const registerFormRef = ref(null)

// 加载状态
const loading = ref(false)

// 登录请求
const handleLogin = async () => {
  if (loginFormRef.value) {
    await loginFormRef.value.validate(async (valid) => {
      if (valid) {
        loading.value = true
        try {
          const res = await login(loginForm)
          if (res.code === 200) {
            // 保存token
            userStore.setToken(res.data)
            // 获取用户信息
            await userStore.getUserInfo()
            // 跳转到首页
            router.push('/')
            ElMessage.success('登录成功')
          } else {
            ElMessage.error(res.message || '登录失败')
          }
        } catch (error) {
          console.error('登录错误', error)
          ElMessage.error('登录失败，请检查网络连接')
        } finally {
          loading.value = false
        }
      }
    })
  }
}

// 注册请求
const handleRegister = async () => {
  if (registerFormRef.value) {
    await registerFormRef.value.validate(async (valid) => {
      if (valid) {
        loading.value = true
        try {
          const res = await register({
            username: registerForm.username,
            password: registerForm.password,
            email: registerForm.email,
            phone: registerForm.phone
          })
          
          if (res.code === 200) {
            ElMessage.success('注册成功，请登录')
            // 切换到登录面板
            activeTab.value = 'login'
            // 预填写用户名
            loginForm.username = registerForm.username
          } else {
            ElMessage.error(res.message || '注册失败')
          }
        } catch (error) {
          console.error('注册错误', error)
          ElMessage.error('注册失败，请检查网络连接')
        } finally {
          loading.value = false
        }
      }
    })
  }
}
</script>

<template>
  <div class="login-container">
    <div class="login-box">
      <div class="header">
        <img src="../assets/order.png" alt="**系统" class="logo" />
        <h1>**系统</h1>
      </div>
      
      <el-tabs v-model="activeTab" class="form-tabs">
        <!-- 登录面板 -->
        <el-tab-pane label="登录" name="login">
          <el-form 
            ref="loginFormRef"
            :model="loginForm"
            :rules="loginRules"
            label-position="top"
          >
            <el-form-item label="用户名" prop="username">
              <el-input
                v-model="loginForm.username"
                placeholder="请输入用户名"
                prefix-icon="User"
              />
            </el-form-item>
            
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码"
                prefix-icon="Lock"
                show-password
                @keyup.enter="handleLogin"
              />
            </el-form-item>
            
            <el-form-item>
              <el-button
                type="primary"
                :loading="loading"
                @click="handleLogin"
                style="width: 100%"
              >
                登录
              </el-button>
            </el-form-item>
            
            <div class="bottom-links">
              <el-button text @click="activeTab = 'register'">
                没有账号？立即注册
              </el-button>
            </div>
          </el-form>
        </el-tab-pane>
        
        <!-- 注册面板 -->
        <el-tab-pane label="注册" name="register">
          <el-form
            ref="registerFormRef"
            :model="registerForm"
            :rules="registerRules"
            label-position="top"
          >
            <el-form-item label="用户名" prop="username">
              <el-input
                v-model="registerForm.username"
                placeholder="请输入用户名"
                prefix-icon="User"
              />
            </el-form-item>
            
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="registerForm.password"
                type="password"
                placeholder="请输入密码"
                prefix-icon="Lock"
                show-password
              />
            </el-form-item>
            
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                v-model="registerForm.confirmPassword"
                type="password"
                placeholder="请确认密码"
                prefix-icon="Lock"
                show-password
              />
            </el-form-item>
            
            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="registerForm.email"
                placeholder="请输入邮箱"
                prefix-icon="Message"
              />
            </el-form-item>
            
            <el-form-item label="手机号" prop="phone">
              <el-input
                v-model="registerForm.phone"
                placeholder="请输入手机号"
                prefix-icon="Phone"
              />
            </el-form-item>
            
            <el-form-item>
              <el-button
                type="primary"
                :loading="loading"
                @click="handleRegister"
                style="width: 100%"
              >
                注册
              </el-button>
            </el-form-item>
            
            <div class="bottom-links">
              <el-button text @click="activeTab = 'login'">
                已有账号？立即登录
              </el-button>
            </div>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: #f0f2f5;
  background-image: url('https://gw.alipayobjects.com/zos/rmsportal/TVYTbAXWheQpRcWDaDMu.svg');
  background-repeat: no-repeat;
  background-position: center;
  background-size: 100%;
}

.login-box {
  width: 400px;
  padding: 30px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.logo {
  height: 60px;
  margin-bottom: 10px;
}

h1 {
  font-size: 22px;
  font-weight: bold;
  color: #333;
  margin: 0;
}

.form-tabs {
  width: 100%;
}

.bottom-links {
  margin-top: 10px;
  text-align: center;
}
</style> 